﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.UI;
using SingleUserMall.Common;
using SingleUserMall.Stores;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SingleUserMall.Configuration
{
    [AbpAuthorize]
    public class ConfigurationManageAppService : SingleUserMallAppServiceBase, IConfigurationManageAppService
    {
        private readonly IRepository<Store> _storeRepository;
        public ConfigurationManageAppService(
            IRepository<Store> storeRepository)
        {
            _storeRepository = storeRepository;
        }

        public async Task<string> GetKeyAsync()
        {
            var key = Pay.WxPay.WxPayContext.H5Instance.GetPublicKey();
            return await Task.FromResult(key);
        }

        public async Task<string> UploadAsync([SwaggerFileUpload(true)] string file)
        {
            try
            {
                var _file = HttpContext.Current.Request.Files[0];
                var (fileUrl, path, size, key) = Upload(_file);
                QiniuContext.Instance.UploadFile(path, key);
                return await Task.FromResult(QiniuContext.Instance.GetUrl(key));
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }

        public async Task<string> UploadVideoAsync([SwaggerFileUpload(true)] string file)
        {
            try
            {
                string filePath = "";
                string url = HttpContext.Current.Request.Url.ToString();
                string absolutePath = HttpContext.Current.Request.Url.AbsolutePath;
                string hostUrl = url.Substring(0, url.IndexOf(absolutePath));
                foreach (var item in HttpContext.Current.Request.Files)
                {
                    HttpFileCollection ff = HttpContext.Current.Request.Files;
                    HttpPostedFile postFile = ff[0];
                    if (postFile.ContentLength == 0)
                        continue;
                    string newFilePath = HttpContext.Current.Request.ApplicationPath + "Video/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(newFilePath)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(newFilePath));
                    }
                    string fileName = newFilePath + "/" + Guid.NewGuid() + "." + postFile.FileName.Split('.').Last();
                    filePath = fileName;
                    postFile.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                }
                return await Task.FromResult(hostUrl + filePath);
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }
}
